package spotGUI.firstRunGUI;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.EmptyBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;

import managers.DBManager;
import utils.MaxLenghtTextDocument;
import utils.LoginRetrievingMethods;
import utils.StackTracePrinter;
import java.util.ResourceBundle;

public class RegistrationPanel extends JPanel {

	private JLabel lblPassword;
	private JComponent lblRepeatPassword;
	private JLabel lblEmail;
	private JTextField nicknameField;
	private JPasswordField repeatPasswordField;
	private JTextField emailField;
	private JLabel lblNickname;
	private JPasswordField passwordField;
	private JLabel lblOldPassword;
	private JPasswordField oldPasswordField;
	protected JTextPane registrationLog;

	protected MutableAttributeSet red;
	protected MutableAttributeSet green;
	protected JButton btnNext;
	protected JProgressBar progressBar;
	private JScrollPane scrollPane;

	private int userId;


	public RegistrationPanel(int userId) {
		setBorder(new EmptyBorder(18, 10, 10, 10));

		this.userId = userId;

		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[]{108, 130, 164, 190, 0};
		gridBagLayout.rowHeights = new int[]{20, 0, 20, 126, 0};
		gridBagLayout.columnWeights = new double[]{0.0, 1.0, 0.0, 1.0, Double.MIN_VALUE};
		gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
		setLayout(gridBagLayout);

		lblNickname = new JLabel(ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.lblNickname.text")); //$NON-NLS-1$ //$NON-NLS-2$
		GridBagConstraints gbc_lblNickname = new GridBagConstraints();
		gbc_lblNickname.anchor = GridBagConstraints.EAST;
		gbc_lblNickname.insets = new Insets(0, 0, 5, 5);
		gbc_lblNickname.gridx = 0;
		gbc_lblNickname.gridy = 0;
		add(lblNickname, gbc_lblNickname);

		nicknameField = new JTextField();
		nicknameField.setToolTipText(ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.nicknameField.toolTipText")); //$NON-NLS-1$ //$NON-NLS-2$
		nicknameField.setDocument(new MaxLenghtTextDocument(25));
		nicknameField.setDocument(new MaxLenghtTextDocument(30));
		nicknameField.setDocument(new MaxLenghtTextDocument(30));
		nicknameField.setMinimumSize(new Dimension(170, 25));
		nicknameField.setPreferredSize(new Dimension(170, 20));
		GridBagConstraints gbc_nicknameField = new GridBagConstraints();
		gbc_nicknameField.fill = GridBagConstraints.VERTICAL;
		gbc_nicknameField.insets = new Insets(0, 0, 5, 5);
		gbc_nicknameField.gridx = 1;
		gbc_nicknameField.gridy = 0;
		add(nicknameField, gbc_nicknameField);

		lblOldPassword = new JLabel(ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.lblOldPassword.text")); //$NON-NLS-1$ //$NON-NLS-2$
		GridBagConstraints gbc_lblOldPassword = new GridBagConstraints();
		gbc_lblOldPassword.anchor = GridBagConstraints.EAST;
		gbc_lblOldPassword.insets = new Insets(0, 0, 5, 5);
		gbc_lblOldPassword.gridx = 2;
		gbc_lblOldPassword.gridy = 0;
		add(lblOldPassword, gbc_lblOldPassword);

		oldPasswordField = new JPasswordField();
		oldPasswordField.setDocument(new MaxLenghtTextDocument(20));
		oldPasswordField.setMinimumSize(new Dimension(130, 25));
		oldPasswordField.setPreferredSize(new Dimension(130, 20));
		GridBagConstraints gbc_oldPasswordField = new GridBagConstraints();
		gbc_oldPasswordField.fill = GridBagConstraints.HORIZONTAL;
		gbc_oldPasswordField.insets = new Insets(0, 0, 5, 0);
		gbc_oldPasswordField.gridx = 3;
		gbc_oldPasswordField.gridy = 0;
		add(oldPasswordField, gbc_oldPasswordField);

		lblPassword = new JLabel(ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.lblPassword.text")); //$NON-NLS-1$ //$NON-NLS-2$
		lblPassword.setToolTipText(ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.lblPassword.toolTipText")); //$NON-NLS-1$ //$NON-NLS-2$
		GridBagConstraints gbc_lblPassword = new GridBagConstraints();
		gbc_lblPassword.anchor = GridBagConstraints.EAST;
		gbc_lblPassword.insets = new Insets(0, 0, 5, 5);
		gbc_lblPassword.gridx = 0;
		gbc_lblPassword.gridy = 1;
		add(lblPassword, gbc_lblPassword);

		passwordField = new JPasswordField();
		passwordField.setDocument(new MaxLenghtTextDocument(20));
		passwordField.setMinimumSize(new Dimension(130, 25));
		passwordField.setPreferredSize(new Dimension(130, 20));
		GridBagConstraints gbc_passwordField = new GridBagConstraints();
		gbc_passwordField.fill = GridBagConstraints.BOTH;
		gbc_passwordField.insets = new Insets(0, 0, 5, 5);
		gbc_passwordField.gridx = 1;
		gbc_passwordField.gridy = 1;
		add(passwordField, gbc_passwordField);

		lblRepeatPassword = new JLabel(ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.lblRepeatPassword.text")); //$NON-NLS-1$ //$NON-NLS-2$
		lblRepeatPassword.setToolTipText(ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.lblRepeatPassword.toolTipText")); //$NON-NLS-1$ //$NON-NLS-2$
		GridBagConstraints gbc_lblRepeatPassword = new GridBagConstraints();
		gbc_lblRepeatPassword.anchor = GridBagConstraints.EAST;
		gbc_lblRepeatPassword.insets = new Insets(0, 0, 5, 5);
		gbc_lblRepeatPassword.gridx = 2;
		gbc_lblRepeatPassword.gridy = 1;
		add(lblRepeatPassword, gbc_lblRepeatPassword);

		repeatPasswordField = new JPasswordField();
		repeatPasswordField.setDocument(new MaxLenghtTextDocument(20));
		repeatPasswordField.setMinimumSize(new Dimension(130, 25));
		repeatPasswordField.setPreferredSize(new Dimension(130, 20));
		GridBagConstraints gbc_repeatPasswordField = new GridBagConstraints();
		gbc_repeatPasswordField.fill = GridBagConstraints.BOTH;
		gbc_repeatPasswordField.insets = new Insets(0, 0, 5, 0);
		gbc_repeatPasswordField.gridx = 3;
		gbc_repeatPasswordField.gridy = 1;
		add(repeatPasswordField, gbc_repeatPasswordField);

		lblEmail = new JLabel(ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.lblEmail.text")); //$NON-NLS-1$ //$NON-NLS-2$
		lblEmail.setToolTipText(ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.lblEmail.toolTipText")); //$NON-NLS-1$ //$NON-NLS-2$
		GridBagConstraints gbc_lblEmail = new GridBagConstraints();
		gbc_lblEmail.anchor = GridBagConstraints.EAST;
		gbc_lblEmail.insets = new Insets(0, 0, 5, 5);
		gbc_lblEmail.gridx = 0;
		gbc_lblEmail.gridy = 2;
		add(lblEmail, gbc_lblEmail);

		scrollPane = new JScrollPane();
		scrollPane.setMinimumSize(new Dimension(25, 100));
		scrollPane.setBorder(null);
		scrollPane.setOpaque(false);
		scrollPane.getViewport().setOpaque(false);

		emailField = new JTextField();
		emailField.setDocument(new MaxLenghtTextDocument(40));
		emailField.setMinimumSize(new Dimension(220, 25));
		emailField.setPreferredSize(new Dimension(220, 20));

		GridBagConstraints gbc_emailField = new GridBagConstraints();
		gbc_emailField.gridwidth = 2;
		gbc_emailField.insets = new Insets(0, 0, 5, 5);
		gbc_emailField.fill = GridBagConstraints.BOTH;
		gbc_emailField.gridx = 1;
		gbc_emailField.gridy = 2;
		add(emailField, gbc_emailField);

		btnNext = new JButton(ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.btnNext.text")); //$NON-NLS-1$ //$NON-NLS-2$
		btnNext.setVisible(true);
		btnNext.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (checkInput() == true) {
					try {
						updateDatabase();
						registrationLog.setText("");
						printMessage(ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.1"), green);
						btnNext.setVisible(false);
					} catch (SQLException e) {
						StackTracePrinter.print(e);
						if (e.getErrorCode() == 1062) {
							printMessage(ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.2"), red);
						} else {
							manageConnectionError();
						}
						
					}
				}
			}
		});
		GridBagConstraints gbc_ntnNext = new GridBagConstraints();
		gbc_ntnNext.insets = new Insets(0, 0, 5, 0);
		gbc_ntnNext.anchor = GridBagConstraints.SOUTH;
		gbc_ntnNext.gridx = 3;
		gbc_ntnNext.gridy = 2;
		add(btnNext, gbc_ntnNext);
		GridBagConstraints gbc_scrollPane = new GridBagConstraints();
		gbc_scrollPane.fill = GridBagConstraints.BOTH;
		gbc_scrollPane.gridwidth = 4;
		gbc_scrollPane.gridx = 0;
		gbc_scrollPane.gridy = 3;
		add(scrollPane, gbc_scrollPane);

		registrationLog = new JTextPane();
		registrationLog.setBorder(null);
		registrationLog.setBackground(new Color(0,0,0,0));
		scrollPane.setViewportView(registrationLog);
		registrationLog.setPreferredSize(new Dimension(6, 180));
		registrationLog.setOpaque(false);
		registrationLog.setEditable(false);

		GridBagConstraints gbc_btnReconnect = new GridBagConstraints();
		gbc_btnReconnect.anchor = GridBagConstraints.SOUTHWEST;
		gbc_btnReconnect.insets = new Insets(0, 0, 0, 5);
		gbc_btnReconnect.gridx = 0;
		gbc_btnReconnect.gridy = 6;

		red = new SimpleAttributeSet();
		red.addAttribute(StyleConstants.CharacterConstants.Foreground, Color.RED.darker().darker());
		red.addAttribute(StyleConstants.Italic, true);

		green = new SimpleAttributeSet();
		green.addAttribute(StyleConstants.CharacterConstants.Foreground, Color.GREEN.darker().darker());
		green.addAttribute(StyleConstants.Italic, true);

		printMessage(ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.3"), green);
		printMessage(ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.4"), null);

	}


	protected void printMessage (String message, MutableAttributeSet attributes) {
		Document doc = registrationLog.getDocument();
		try {
			doc.insertString(doc.getLength(), message+"\n", attributes);
		} catch (BadLocationException e) {
			StackTracePrinter.print(e);
		}
	}


	private boolean checkInput () {

		boolean valid = true;
		registrationLog.setText("");

		String nickName = nicknameField.getText();
		char[] oldPassword = oldPasswordField.getPassword();
		char[] password = passwordField.getPassword();
		char[] repeatPassword = repeatPasswordField.getPassword();
		String email = emailField.getText();


		if (oldPassword.length == 0) {
			printMessage (ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.6"), red);
			valid = false;
		} else {
			try {
				String pswd = (String)LoginRetrievingMethods.getPassword(DBManager.getConnection(),
						Integer.toString(userId), LoginRetrievingMethods.ID)[0];
				if (!(new String(oldPasswordField.getPassword()).equals(pswd))) {
					printMessage (ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.7"), red);
					valid = false;
				}
			} catch (SQLException e) {
				StackTracePrinter.print(e);
				manageConnectionError();
			}
		}
		if (password.length == 0) {
			printMessage (ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.8"), red);
			valid = false;
		}
		if (repeatPassword.length == 0) {
			printMessage (ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.9"), red);
			valid = false;
		}
		if (password.length != 0 && repeatPassword.length != 0 && !(new String(password).equals(new String(repeatPassword)))) {
			printMessage (ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.10"), red);
			valid = false;
		}
		int i = 0;
		if (email.length() == 0) {
			printMessage (ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.11"), red);
			valid = false;
		} else {
			if (email.contains("'") || email.contains("?") || email.contains("!")) {
				printMessage (ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.12"), red);
				valid = false;
			}
			while ((i < email.length() && email.charAt(i) != '@')) {
				i++;
			}
			if (i == email.length()) {
				printMessage (ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.13"), red);
				valid = false;
			}
			i++;
			while ((i < email.length() && email.charAt(i) != '.')) {
				i++;
			}
			if (i == email.length()) {
				printMessage (ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.13"), red);
				valid = false;
			}
		}
		return valid;
	}

	private void manageConnectionError() {
		registrationLog.setText("");
		printMessage(ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.14"), red);
	}

	private void updateDatabase () throws SQLException  {

		DBManager.getConnection();

		printMessage(ResourceBundle.getBundle("spotGUI.firstRunGUI.messages").getString("RegistrationPanel.15"), green);
		Connection conn = DBManager.getConnection();
		Statement stmt = conn.createStatement();
		String nickPart = nicknameField.getText().length()>0?"',nickname='"+nicknameField.getText().replace("'", "\\'")+"',":" "; 
		String query = "update spotmessenger.USERS set password='"+new String(passwordField.getPassword())+"', email='"+emailField.getText()+", "
				+ nickPart + "registered=true where id="+userId;
		stmt.executeUpdate(query);
		DBManager.closeResources(stmt, null);
	}
}

